<template>
	<view>
		<view style="height: 40px;"></view>
		<view style=" font-size: 25px;font-weight: bold;color: #000;margin-bottom: 15px;padding: 20px;">
			欢迎进入lilishop
		</view>

		<!-- 登录表单 -->
		<view class="login-form">
			<view class="form-item">
				<u-input
					v-model="loginForm.username"
					placeholder="请输入用户名"
					border="surround"
					:clearable="true"
					style="width: 100%;"
				></u-input>
			</view>
			<view class="form-item">
				<u-input
					v-model="loginForm.password"
					placeholder="请输入密码"
					border="surround"
					:clearable="true"
					:password="true"
					style="width: 100%;"
				></u-input>
			</view>
		</view>

		<view style="height: 20px;"></view>
		<u-button type="success" shape="circle" size="large" style="width: 80%;" text="登录"
			@click="handleLogin" :loading="isLogging"></u-button>
		<view style="height: 20px;"></view>
		<u-button type="default" shape="circle" size="large" color="#EDEDED" style="color: #000; width: 80%;"
			text="注册" @click="handleRegister"></u-button>

		<!-- 协议确认区域 -->
		<view class="agreement-container">
			<view class="agreement-item" @click="toggleAgree">
				<!-- 单选圆圈 -->
				<view class="radio-circle" :class="{checked: isAgreed}">
					<view class="checkmark" v-if="isAgreed">✓</view>
				</view>
				<view class="xieyi" style="display: flex; align-items: center; white-space: nowrap;">
					<text>阅读并同意</text>
					<text @click="navigateTo('privacy')" style="color: #FF6B35 ">《隐私协议》</text>
					<text @click="navigateTo('user')" style="color: #FF6B35 ">《用户协议》</text>
				</view>
			</view>
		</view>
		<!-- 提示弹窗 -->
		<u-modal :show="showAlert" title="提示" content="请先阅读并同意用户协议和隐私协议" :showCancelButton="true"
			@confirm="showAlert = false" @cancel="showAlert = false"></u-modal>
		<!-- 登录中加载弹窗 -->
		<view class="login-mask" v-if="showLoading">
			<view class="login-dialog">
				<view class="loading-ring"></view>
				<view style="color: white;font-size: 16px;">登录中...</view>
			</view>
		</view>
	</view>
</template>

<script>
	import { post } from '@/config/request.js'
	import webSocketManager from '@/utils/websocket.js'
	import { setUserInfo } from '@/utils/userState.js'

	export default {
		data() {
			return {
				loginForm: {
					username: '',
					password: ''
				},
				isAgreed: false,
				showAlert: false,
				showLoading: false,
				isLogging: false,
				userInfo: null
			}
		},
		onLoad() {
			// 页面加载时检查是否已登录
			this.checkLoginStatus();
		},
		methods: {
			checkLoginStatus() {
				// 检查本地存储的登录状态
				const token = uni.getStorageSync('userToken');
				const userInfo = uni.getStorageSync('userInfo');
				
				if (token && userInfo) {
					// 已登录，直接跳转到我的页面
					this.userInfo = userInfo;
					uni.switchTab({
						url: '/pages/wode/wode'
					});
				}
			},
			toggleAgree() {
				this.isAgreed = !this.isAgreed
			},
			navigateTo(type) {
				// 根据类型跳转不同页面
				const urlMap = {
					privacy: '/pages/login/yinsixieyi',
					user: '/pages/login/user'
				};
				uni.navigateTo({
					url: urlMap[type]
				});
			},
			// 表单校验
			validateForm() {
				if (!this.loginForm.username.trim()) {
					uni.showToast({ title: '请输入用户名', icon: 'none' });
					return false;
				}
				if (!this.loginForm.password.trim()) {
					uni.showToast({ title: '请输入密码', icon: 'none' });
					return false;
				}
				if (!this.isAgreed) {
					this.showAlert = true;
					return false;
				}
				return true;
			},
			async handleLogin() {
				if (!this.validateForm()) return;
				this.isLogging = true;
				this.showLoading = true;
				try {
					await this.performLogin();
				} catch (error) {
					console.error('登录失败:', error);
					uni.showToast({ title: error.message || '登录失败，请重试', icon: 'none' });
				} finally {
					this.isLogging = false;
					this.showLoading = false;
				}
			},
			async performLogin() {
				const res = await post('/Login1/login2/login3', {
					username: this.loginForm.username,
					password: this.loginForm.password
				});
				// 按后端返回格式处理：code/msg/data(token)/user
				if (!res || res.code !== 200) {
					throw new Error(res?.msg || '登录失败');
				}
				const token = "Bearer "+res.data; // token 在 data
				const user = res.user;  // 用户信息在 user
				if (!token) throw new Error('未返回token');
				if (!user) throw new Error('未返回用户信息');
				
				// 确保用户信息包含memberId
				if (!user.memberId) {
					console.warn('用户信息中缺少memberId，尝试从其他字段获取');
					// 尝试从其他可能的字段获取memberId
					user.memberId = user.id || user.member_id || user.userId;
				}
				
				this.saveLoginInfo(user, token);
				uni.showToast({ title: '登录成功', icon: 'success', duration: 1200 });
				setTimeout(() => {
					uni.switchTab({ url: '/pages/wode/wode' });
				}, 1200);
			},
			saveLoginInfo(userInfo, token) {
				// 保存用户信息到本地存储
				console.log(token,"toekn")
				console.log('保存的用户信息:', userInfo)
				
				// 使用userState.js的方法来保存用户信息
				setUserInfo(userInfo);
				
				// 同时保存到原有的存储键中（保持兼容性）
				uni.setStorageSync('userInfo', userInfo);
				uni.setStorageSync('userToken', token);
				uni.setStorageSync('token', token); // 兼容 request.js 的 Authorization
				uni.setStorageSync('isLogin', true);
				
				// 更新状态
				this.userInfo = userInfo;
				
				// 登录成功后建立WebSocket连接
				if (userInfo && userInfo.memberName) {
					console.log('登录成功，建立WebSocket连接，用户名:', userInfo.memberName)
					webSocketManager.connect(userInfo.memberName)
				}
			},
			// 处理注册
			handleRegister() {
				uni.navigateTo({
					url: '/pages/login/zhuce/zhuce'
				});
			}
		}
	}
</script>

<style scoped>
	.login-form { padding: 0 20px; }
	.form-item { margin-bottom: 15px; }

	.agreement-container {
		margin-top: 30px;
		padding: 5px 50px;
	}
	.agreement-item {
		display: flex;
		align-items: center;
	}
	.radio-circle {
		flex-shrink: 0;
		width: 20px;
		height: 20px;
		border: 1px solid #ddd;
		border-radius: 50%;
		margin-right: 10px;
		display: flex;
		justify-content: center;
		align-items: center;
		transition: all 0.2s;
	}

	.radio-circle.checked { background-color: #FF6B35; border-color: #FF6B35; }

	.checkmark { color: white; font-size: 14px; font-weight: bold; }

	/* 登录中弹窗样式 */
	.login-mask {
		position: fixed;
		top: 0; left: 0; right: 0; bottom: 0;
		background-color: rgba(0, 0, 0, 0.5);
		display: flex; justify-content: center; align-items: center;
		z-index: 999;
	}
	.login-dialog {
		width: 200px; height: 160px; background-color: #333; border-radius: 12px;
		display: flex; flex-direction: column; justify-content: center; align-items: center; padding: 20px;
	}
	.loading-ring {
		width: 50px; height: 50px; border: 4px solid #ccc; border-top-color: #FF6B35; border-radius: 50%;
		animation: spin 1s linear infinite; margin-bottom: 20px;
	}
	@keyframes spin { 0% { transform: rotate(0deg);} 100% { transform: rotate(360deg);} }
</style>